package com.wj.spingcloud.controller;

import com.wj.spingcloud.entity.CommonResult;
import com.wj.spingcloud.entity.PaymentEntity;
import com.wj.spingcloud.lb.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @description:
 * @author: wj
 * @create: 2021/5/12 11:19
 */
@RestController
@Slf4j
public class OrderController {

    private static String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalance loadBalance;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/customer/payment/create")
    public CommonResult<PaymentEntity> create(PaymentEntity paymentEntity){
        return restTemplate.postForObject(PAYMENT_URL + "/provider/payment/create", paymentEntity, CommonResult.class);
    }

    @GetMapping("/customer/payment/get/{id}")
    public CommonResult<PaymentEntity> get(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/provider/payment/get/"+id, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/for/entity/{id}")
    public CommonResult<PaymentEntity> getPayment2(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/provider/payment/get/"+id, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()){
            log.info("code:" + entity.getStatusCode() + "\t header:" + entity.getHeaders());
            return entity.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (serviceInstances == null || serviceInstances.size() <= 0){
            return null;
        }

        ServiceInstance serviceInstance = loadBalance.instance(serviceInstances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/provider/payment/lb", String.class);
    }

    @GetMapping("/consumer/payment/zipkin")
    public String getPaymentZipkin(){
        return restTemplate.getForObject("http://localhost:8001" + "/provider/payment/zipkin", String.class);
    }
}